use std::fs::File;
use std::io::Write;
use reqwest::header::{HeaderValue};
extern crate serde_json;
use serde_json::Value;
use std::env;
extern crate wallpaper;
use image::{open, ImageFormat};

#[tokio::main]
async fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
    let client = reqwest::Client::builder()
        .user_agent(HeaderValue::from_static("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"))
        .build()?;
    let api_url = "https://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1";
    let resp = client.get(api_url).send().await?.text().await?;
    let resp_json = serde_json::from_str::<Value>(&resp)?;
    let suffix_url = &resp_json["images"][0]["url"];
    let suffix_url = suffix_url.as_str().unwrap().trim_matches('"');
    let bing_url = "https://www.cn.bing.com";
    let image_url = format!("{}{}", &bing_url, &suffix_url);
    println!("image url:{}", image_url);

    let image_bytes = client.get(&image_url).send().await?.bytes().await?.to_vec();
    println!("image_bytes.len() = {}", image_bytes.len());

    let current_dir = env::current_dir()?;
    let image_path = current_dir.join("wallpaper.jpg");
    let bmp_path = current_dir.join("wallpaper.bmp");
    let mut file = File::create(&image_path)?;
    file.write_all(image_bytes.as_slice())?;
    file.sync_all()?;
    println!("image download finished!");

    let image_path_str = image_path.to_str().unwrap();
    let bmp_path_str = bmp_path.to_str().unwrap();
    jpg2bmp(image_path_str, bmp_path_str)?;

    println!("image path: {}", image_path_str);
    wallpaper::set_from_path(&bmp_path_str).unwrap();
    println!("{:?}", wallpaper::get());
    println!("set wallpaper finished!");

    Ok(())
}

fn jpg2bmp(jpg_path: &str, bmp_path: &str) -> std::io::Result<()> {
    let img = open(jpg_path).unwrap();
    img.save(bmp_path).unwrap();
    Ok(())
}
